﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.ResourceManagement.Client;
using Microsoft.ResourceManagement.ObjectModel;

namespace Ensynch.FIM
{
    public class ObjectResolverQuery : FimQuery
    {
        // 16 Xpath 'or' conditions seems to be the sweet spot.
        public const int OBJECT_RESOLVER_BATCH_SIZE = 16;

        private List<string> objects = new List<string>();
        private string defaultXpath;

        public ObjectResolverQuery(string defaultXpath, FimTools tools)
            : base(tools)
        {
            _query = rawXPath = this.defaultXpath = defaultXpath;
            log.Debug("[.ctor] _query reset to: " + _query.ToString());
        }

        public void ClearObjects()
        {
            objects.Clear();
            // Reset the xpath & query.
            _query = rawXPath = this.defaultXpath;
            log.Debug("[ClearObjects] _query reset to: " + _query.ToString());
        }

        public void AddObject(string obj)
        {
            objects.Add(obj);
            // Rebuild the xpath & query every time.
            _query = rawXPath = buildXPath(objects.ToArray());
            log.Debug("[AddObject] _query reset to: " + _query.ToString());
        }

        #region Not worth it
        //protected override string queryForObjectType(string xpath)
        //{
        //    string objectType = null;

        //    foreach (string obj in objects)
        //    {
        //        string newXpath = buildXPath(new string[] { obj });
        //        objectType = base.queryForObjectType(newXpath);
        //        if (objectType != null)
        //        {
        //            break;
        //        }
        //    }

        //    return objectType;
        //}
        #endregion

        private string buildXPath(string[] objs)
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append("/*[");

            bool first = true;
            foreach (string obj in objs)
            {
                if (!first)
                {
                    buffer.Append(" or ");
                }
                buffer.AppendFormat("ObjectID = '{0}'", obj);
                first = false;
            }

            buffer.Append("]");
            return buffer.ToString();
        }
    }
}
